package com.haixiaoke.saas.repository.orderStateMachine;

import com.alibaba.cola.statemachine.Action;
import com.alibaba.cola.statemachine.StateMachine;
import com.alibaba.cola.statemachine.builder.StateMachineBuilder;
import com.alibaba.cola.statemachine.builder.StateMachineBuilderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 状态机初始化
 */
@Configuration
public class StateMachineRegister {
    private static final Logger logger = LoggerFactory.getLogger(StateMachineRegister.class);

    private final String STATE_MACHINE_ID = "orderStateMachineId";

    /**
     * 构建状态机实例
     */
    @Bean
    public StateMachine<OrderStateEnum, Event, orderContext> stateMachine() {

        StateMachineBuilder<OrderStateEnum, Event, orderContext> stateMachineBuilder = StateMachineBuilderFactory.create();
        // 订单流转触发事件
        // 因为没有源状态，初始化时只是同一个状态流转，所以用内部流转
        stateMachineBuilder.internalTransition().within(OrderStateEnum.ORDER_STATE_PAYMENT).on(Event.PAY_ORDER).perform(doAction());
        // 用户签订合同事件

        // 用户入住触发事件（依赖上一个状态：ORDER_STATE_PAYMENT
        stateMachineBuilder.externalTransition()
                .from(OrderStateEnum.ORDER_STATE_PAYMENT)
                .to(OrderStateEnum.ORDER_STATE_CHECK_IN)
                .on(Event.CHECK_IN)
                .perform(doAction());
        return stateMachineBuilder.build(STATE_MACHINE_ID);

    }


    /**
     * 事件触发后，匹配成功对应的条件后，就会执行具体动作<br>
     * 可以自定义完成具体业务逻辑...
     *
     * @return
     */
    private Action<OrderStateEnum, Event, orderContext> doAction() {
        return (from, to, event, ctx) -> {
            // 存储数据库
            System.out.println("from:" + from + " to:" + to + " on:" + event + " condition:" + ctx);
        };
    }


}
